
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
layui.use(['tableEdit',"excel","selectInput"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel,
        selectInput = layui.selectInput;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }
    function getxmselectUser(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            initValue:[user.code],
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }
    let operationList=[];
    let billNoStatusList=[];
    let deptOperationList=[];
    layer.ready(function () {
        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();
        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            operationList=getxmselectUser("#operationCode", "operationCode", userTree);
        } else {
            operationList=getxmselectUser("#operationCode", "operationCode", [{name: user.name, value: user.code}])
        }
        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptOperationList = getxmselectUser("#deptOperationCode", "deptOperationCode", deptTree);
        } else {
            deptOperationList = getxmselectUser("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        }

        //单据信息
        let billNoStatus = [
            {name: "草稿箱", value: "1"},
            {name: "待批箱", value: "2,2.1"},
            {name: "已批箱", value: "3"},
            {name: "终止箱", value: "6"},
            {name: "完成箱", value: "4"},
            {name: "垃圾箱", value: "5"}
        ];
        billNoStatusList=getxmselect("#status", "status", billNoStatus);

    });
    form.render();//表单刷新

    table.render({
        elem: '#offerselect'
        , data: []
        , toolbar: '#offertoolbar'
        ,totalRow: true
        , cols: [[
            {field: 'numbers', width: 50, type: 'numbers', title: '序号', totalRowText: '合计'}
            , {field: 'status', title: '单据类型', width: 120, sort: true}
            , {field: 'supplierName', title: '供应商名称', sort: true, width: 120}
            , {field: 'purchaseOrderNo', width: 120, title: '采购单号', sort: true}
            , {field: 'signTimeStr', title: '签约日期', sort: true, width: 120}
            , {field: 'supplierAccountPeriod', title: '供应商账期', sort: true, width: 120}
            , {field: 'payableDateStr', title: '应付日期', sort: true, width: 120}
            , {field: 'executorName', title: '操作员', sort: true, width: 120}
            , {field: 'paymentType', title: '付款类型', sort: true, width: 120}
            , {field: 'earnestRate', width: 120, title: '定金比例', sort: true}
            , {field: 'earnestAmount', width: 120, title: '定金总额', sort: true}
            , {field: 'totalPurchaseAmount', width: 160, title: '采购合同总额', sort: true}
            , {field: 'taxIncluded', title: '是否含税', sort: true, width: 120}
            , {field: 'paymentBillNo', title: '付款单号', width: 200}
            , {field: 'applicationAmount', title: '已申请金额',width: 120, sort: true}
            , {field: 'unApplicationAmount', title: '未申请金额', width: 120, totalRow: true}
            , {field: 'totalAmountActuallyPaid', title: '实付金额', sort: true, width: 120, totalRow: true}
            , {field: 'productNo', title: '产品编码', sort: true, width: 120}
            , {field: 'specNo', title: '规格编码', sort: true, width: 220}
            , {field: 'chineseName', title: '中文名称', sort: true, width: 120}
            , {field: 'englishName', title: '英文名称', sort: true, width: 120}
            , {field: 'chineseDesc', width: 120, title: '中文描述'}
            , {field: 'englishDesc', width: 120, title: '英文描述'}
            , {field: 'normExplain', title: '规格说明', sort: true, width: 120}
            , {field: 'amount', title: '产品数量', sort: true, width: 120, totalRow: true}
            , {field: 'productUnitPrice', title: '产品单价', sort: true, width: 120}
            , {field: 'price', title: '采购成本', sort: true, width: 120}
            , {field: 'otherCost', title: '其它费用', sort: true, width: 120}
            , {field: 'memoOfCost', title: '费用备注', sort: true, width: 120}
            , {field: 'memo', title: '单据备注', sort: true, width: 120}
            , {field: 'materialSupplierName', title: '素材供应商', sort: true, width: 120}
            , {field: 'purchaseType', title: '采购类型', sort: true, width: 120}

        ]]
        , id: 'offertableid'
        , height: $(document).height() - $('#offerselect').offset().top - 50
        , page: true
        , limit: 300
        , limits: [300, 600, 900]
    });


    form.on('submit(submitform)', function (data) {
        if (isEmpty(operationList.getValue('valueStr'))  && isEmpty(deptOperationList.getValue('valueStr'))){
            data.field.operationCode= user.code
        }
        table.reload('offertableid', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , url: 'purchase/purchaseSampleStatisticsByPage'
            , where: data.field
        }, 'data');
        return false;
    });


    form.on('submit(exportData)', function (queryReq) {
        if (isEmpty(operationList.getValue('valueStr'))  && isEmpty(deptOperationList.getValue('valueStr'))){
            queryReq.field.operationCode= user.code
        }
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url:"purchase/purchaseSampleStatisticsExport",
            success: function(res) {
                if(res.status == 200){
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 80,
                        'X': 80
                    }, 80);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '样品采购付款详情.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });
    document.getElementById('clear').onclick = function(){
        billNoStatusList.setValue([ ]);
        operationList.setValue([ ]);
        deptOperationList.setValue([ ]);
    };
    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
});